package frsf.cidisi.exercise.tp1_ia.search.actions;

import frsf.cidisi.exercise.tp1_ia.search.*;
import frsf.cidisi.faia.agent.search.SearchAction;
import frsf.cidisi.faia.agent.search.SearchBasedAgentState;
import frsf.cidisi.faia.state.AgentState;
import frsf.cidisi.faia.state.EnvironmentState;

public class EndSubProcess_3 extends SearchAction {

	int tiempo_actividad = -1;
	int tiempo_accion = -1;
    /**
     * This method updates a tree node state when the search process is running.
     * It does not updates the real world state.
     */
    @Override
    public SearchBasedAgentState execute(SearchBasedAgentState s) {
        EstadoAgente agState = (EstadoAgente) s;
        ini();    	
    	
        if((agState.getposicionAgente() == EstadoAgente.ACCEPT_PROPOSAL_SENT ||
        		agState.getposicionAgente() == EstadoAgente.UPDATED_DEMAND_FORECAST_SENT) &&
        		!agState.isCanceled()){
        	agState.setposicionAgente(EstadoAgente.SUBPROCESS_3_FINALIZED);
        	agState.settpoTranscurrido(1);
        	return agState;
        }
        
        return null;
    }
    
    private void ini() {
    	if(tiempo_actividad == -1){
    		tiempo_actividad = ComputersMarketPerception.aleatorio(10, 20);
    	}    	
    	if(tiempo_accion == -1){
    		tiempo_accion = ComputersMarketPerception.aleatorio(1, 3);
    	}		
	}

    /**
     * This method updates the agent state and the real world state.
     */
    @Override
    public EnvironmentState execute(AgentState ast, EnvironmentState est) {
    	ini();   	
    	
        EstadoAmbiente environmentState = (EstadoAmbiente) est;
        EstadoAgente agState = ((EstadoAgente) ast);

        if((agState.getposicionAgente() == EstadoAgente.ACCEPT_PROPOSAL_SENT ||
        		agState.getposicionAgente() == EstadoAgente.UPDATED_DEMAND_FORECAST_SENT)&&
        		agState.getPerceptionName().equals("Propose Demand Forecast2")) {
            // Update the agent state
        	agState.setposicionAgente(EstadoAgente.SUBPROCESS_3_FINALIZED);
        	agState.settpoTranscurrido(1);
        	// Update the real world
        	environmentState.setposicionAgente(EstadoAgente.SUBPROCESS_3_FINALIZED);
        	environmentState.settpoTranscurrido(1);
 
        	return environmentState;
        }

        return null;
    }


    /**
     * This method returns the action cost.
     */
    @Override
    public Double getCost() {
        return new Double(1);
    }

    /**
     * This method is not important for a search based agent, but is essensial
     * when creating a calculus based one.
     */
    @Override
    public String toString() {
        return "SubProcess 3 Finalized | tiempo: " + this.getCost();
    }
}